<script setup>
import { ref, onMounted ,watch ,nextTick } from 'vue'
import router from '@/router/index.js'
import { useRoute } from 'vue-router'
import { getSearchAll, searchHotelsByKeyword } from '../api/hotel.js'
import dayjs from 'dayjs'

// 响应式变量
const hotelList = ref([])
const location = ref('')
const checkInDate = ref('')
const checkOutDate = ref('')
const roomCount = ref(1)
const selectedPrice = ref(null)
const selectedRating = ref(null)
const selectedType = ref(null)
const selectedRoomType = ref(null)

const route = useRoute()




location.value = route.query.keyword || ''
checkInDate.value = route.query.checkInDate || ''
checkOutDate.value = route.query.checkOutDate || ''
roomCount.value = route.query.roomCount || 1


// 如果没有传时间，就设置默认值：今天和明天
if (!checkInDate.value) {
  checkInDate.value = dayjs().format('YYYY-MM-DD')
}
if (!checkOutDate.value) {
  checkOutDate.value = dayjs().add(1,'day').format('YYYY-MM-DD')
}

// 点击酒店跳转
const toHotelDetail = (hotelId) => {
  router.push(`hDetail/${hotelId}`)
}

// 解析 ES 返回的带 <em> 的字符串
const parseHighlightText = (rawText) => {
  if (!rawText) return [{ text: '', isHighlight: false }]
  const regex = /<em.*?>(.*?)<\/em>/g
  const result = []
  let lastIndex = 0
  let match
  while ((match = regex.exec(rawText)) !== null) {
    if (match.index > lastIndex) {
      result.push({
        text: rawText.slice(lastIndex, match.index),
        isHighlight: false
      })
    }
    result.push({
      text: match[1],
      isHighlight: true
    })
    lastIndex = regex.lastIndex
  }
  if (lastIndex < rawText.length) {
    result.push({
      text: rawText.slice(lastIndex),
      isHighlight: false
    })
  }
  return result
}

// ES 返回后，生成 highlightName 和 highlightAddress
const processHotelHighlight = (hotels) => {
  return hotels.map(h => {
    const name = h.hotelName || h.name || ''
    const address = `${h.province || ''}-${h.county || ''}-${h.street || ''}`
    return {
      ...h,
      highlightName: parseHighlightText(name),
      highlightAddress: parseHighlightText(address)
    }
  })
}

// 页面加载：首页 keyword 搜索或多条件搜索
const loadHotels = async () => {
  if (location.value) {
    const hotels = await searchHotelsByKeyword(location.value)
    hotelList.value = processHotelHighlight(hotels)
  } else {
    await searchHotels()
  }
}

// 多条件查询（SQL）
const searchHotels = async () => {
  const requestParams = {
    location: location.value || null,
    checkInDate: checkInDate.value || null,
    checkOutDate: checkOutDate.value || null,
    roomCount: Number(roomCount.value) || 1,
    minPrice: selectedPrice.value?.split('-')[0] ? Number(selectedPrice.value.split('-')[0]) : null,
    maxPrice: selectedPrice.value?.split('-')[1] ? Number(selectedPrice.value.split('-')[1]) : null,
    star: selectedRating.value ? Number(selectedRating.value) : null,
    type: selectedType.value,
    roomType: selectedRoomType.value
  }
  const res = await getSearchAll(requestParams)
  hotelList.value = processHotelHighlight(res.data?.data || [])
}

// 筛选函数：调用 SQL 多条件搜索
const filterByPrice = (min, max) => {
  selectedPrice.value = max === Infinity ? `${min}+` : `${min}-${max}`
  searchHotels()
}
const filterByRating = (rating) => {
  selectedRating.value = rating
  searchHotels()
}
const filterByType = (type) => {
  selectedType.value = type
  searchHotels()
}
const filterByRoomType = (roomType) => {
  selectedRoomType.value = roomType
  searchHotels()
}

// 从路由参数同步到本地状态
const normalizeQuery = () => {
  location.value = route.query.keyword || ''
  checkInDate.value = route.query.checkInDate
    ? dayjs(route.query.checkInDate).format('YYYY-MM-DD')
    : dayjs().format('YYYY-MM-DD')
  checkOutDate.value = route.query.checkOutDate
    ? dayjs(route.query.checkOutDate).format('YYYY-MM-DD')
    : dayjs().add(1, 'day').format('YYYY-MM-DD')
  roomCount.value = route.query.roomCount || 1
}

// 页面加载调用
onMounted(() => {
  const initLoad = async () => {
    console.log('✅ 初始加载参数:', route.query)
    normalizeQuery()
    await nextTick() // ✅ 等待参数同步
    console.log('✅ 当前 location 值:', location.value)
    await loadHotels() // ✅ 加载数据
  }

  if (Object.keys(route.query).length > 0) {
    initLoad()
  }

  const stopWatch = watch(
    () => route.query,
    (newQuery) => {
      console.log('✅ 路由参数更新，加载数据:', newQuery)
      if (Object.keys(newQuery).length > 0) {
        initLoad()
        stopWatch()
      }
    },
    { deep: true }
  )
})

</script>

<template>
  <div class="page-wrapper">
    <div class="container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <div class="search-group">
          <input v-model="location" type="text" placeholder="请输入地点或酒店名称" class="search-input" />
          <el-date-picker v-model="checkInDate" type="date" placeholder="入住日期" value-format="YYYY-MM-DD" class="search-input" />
          <el-date-picker v-model="checkOutDate" type="date" placeholder="退房日期" value-format="YYYY-MM-DD" class="search-input" />
          <input v-model="roomCount" type="number" placeholder="预定房间数" class="search-input" />
        </div>
        <button @click="searchHotels" class="search-button">搜索</button>
      </div>

      <div class="content">
        <!-- 左侧过滤栏 -->
        <div class="filters">
          <div class="filter-group">
            <h3>价格范围</h3>
            <button :class="{'active': selectedPrice === '100-500'}" @click="filterByPrice(100, 500)">100-500</button>
            <button :class="{'active': selectedPrice === '500-1000'}" @click="filterByPrice(500, 1000)">500-1000</button>
            <button :class="{'active': selectedPrice === '1000+'}" @click="filterByPrice(1000, Infinity)">1000以上</button>
          </div>
          <div class="filter-group">
            <h3>评分</h3>
            <button v-for="i in 5" :key="i" :class="{'active': selectedRating === i}" @click="filterByRating(i)">{{ i }}星</button>
          </div>
          <div class="filter-group">
            <h3>酒店类型</h3>
            <button :class="{'active': selectedType === '商务'}" @click="filterByType('商务')">商务</button>
            <button :class="{'active': selectedType === '度假'}" @click="filterByType('度假')">度假</button>
            <button :class="{'active': selectedType === '豪华'}" @click="filterByType('豪华')">豪华</button>
          </div>
          <div class="filter-group">
            <h3>房型</h3>
            <button :class="{'active': selectedRoomType === '单人间'}" @click="filterByRoomType('单人间')">单人间</button>
            <button :class="{'active': selectedRoomType === '双人间'}" @click="filterByRoomType('双人间')">双人间</button>
            <button :class="{'active': selectedRoomType === '套房'}" @click="filterByRoomType('套房')">套房</button>
          </div>
        </div>

        <!-- 右侧酒店列表 -->
        <div class="hotel-list">
          <div v-for="hotel in hotelList" :key="hotel.hotelId || hotel.id" class="hotel-card">
            <div class="hotel-image">
              <img :src="hotel.hotelImage || hotel.image" alt="酒店图片" />
            </div>
            <div class="hotel-info">
              <h4>
                <span v-for="(part, idx) in hotel.highlightName" :key="idx" :class="{ highlight: part.isHighlight }">
                  {{ part.text }}
                </span>
              </h4>
              <p>
                地址：
                <span v-for="(part, idx) in hotel.highlightAddress" :key="idx" :class="{ highlight: part.isHighlight }">
                  {{ part.text }}
                </span>
              </p>
              <p>评分：{{ hotel.hotelRating || hotel.rating }}</p>
              <p>星级：{{ hotel.hotelStar || '暂无' }}</p>
              <button @click="toHotelDetail(hotel.hotelId || hotel.id)" class="hotel-details-btn">查看详情</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: Arial, sans-serif; background-color: #f4f4f4; min-height: 100vh; }

.page-wrapper { display: flex; justify-content: center; padding: 20px; }
.container { display: flex; flex-direction: column; width: 95%; max-width: 1600px; height: calc(100vh - 40px); background-color: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }

.search-bar { width: 100%; padding: 15px 20px; background-color: #f8f8f8; display: flex; gap: 10px; position: sticky; top: 0; z-index: 1000; align-items: center; }
.search-group { display: flex; gap: 10px; flex-wrap: wrap; flex: 1; background-color: #fff; padding: 10px 12px; border-radius: 10px; border: 1px solid #ddd; box-shadow: 0 2px 4px rgba(0,0,0,0.08); }
.search-input { padding: 8px; border: none; border-radius: 5px; min-width: 120px; flex: 1; border: solid 1px rgb(190, 182, 182); }
.search-button { padding:10px 20px; background-color:#007bff; color:white; border:none; border-radius:5px; cursor:pointer; }

.content { display: flex; flex: 1; gap: 20px; overflow: hidden; }
.filters { width: 300px; padding: 10px 20px; background-color: #f8f8f8; border-radius: 10px; position: sticky; top: 0; align-self: flex-start; height: 100%; overflow-y: auto; box-sizing: border-box; }
.filter-group { margin-bottom: 20px; }
.filter-group h3 { margin-bottom: 10px; }
.filter-group button { display: block; width: 100%; padding: 8px; margin-bottom: 5px; background-color: #fff; border:1px solid #ddd; border-radius:5px; cursor:pointer; font-size:14px; }
.filter-group button.active { background-color: #007bff; color:white; }

.hotel-list { flex: 1; padding: 20px; background-color: #f9f9f9; border-radius: 10px; display: flex; flex-direction: column; overflow-y: auto; }
.hotel-card { background-color: #fff; border-radius: 10px; box-shadow:0 0 10px rgba(0,0,0,0.1); display:flex; margin-bottom:20px; overflow:hidden; position: relative; min-height: 180px; }
.hotel-image img { width: 200px; height: 180px; object-fit: cover; border-radius: 10px 0 0 10px; }
.hotel-info { padding:15px; flex:1; }
.hotel-info h4 { font-size: 18px; margin-bottom:10px; }
.hotel-info p { margin-bottom:5px; }
.hotel-details-btn { padding:8px 12px; background-color:#007bff; color:white; border:none; border-radius:5px; cursor:pointer; font-size:14px; position:absolute; bottom:15px; right:15px; }
.hotel-info button:hover { background-color:#0056b3; }
.highlight { color: red; }

/* 滚动条美化 */
.filters::-webkit-scrollbar, .hotel-list::-webkit-scrollbar { width: 8px; }
.filters::-webkit-scrollbar-track, .hotel-list::-webkit-scrollbar-track { background: transparent; }
.filters::-webkit-scrollbar-thumb, .hotel-list::-webkit-scrollbar-thumb { background-color: rgba(0,0,0,0.2); border-radius: 4px; }
.filters::-webkit-scrollbar-thumb:hover, .hotel-list::-webkit-scrollbar-thumb:hover { background-color: rgba(0,0,0,0.35); }
.filters, .hotel-list { scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent; }
</style>
